package com.weme.common.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText // 使用 AppCompatEditText 替代 EditText
import com.weme.common.R

class SmoothRoundedEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatEditText(context, attrs, defStyleAttr) {
    private var paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var path: Path = Path()
    private var rectF: RectF = RectF()
    var roundPath: SmootRoundedPath = SmootRoundedPath()
    private var leftRadius = 0F
    private var rightRadius = 0F
    private var topRadius = 0F
    private var bottomRadius = 0F
    private var rectColor = Color.WHITE
    private var drawBorderOnly = false
    private var strokeWidth = 1F

    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.SmoothRoundedRectView, defStyleAttr, 0)
        val cornerRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_radius, -1)
        leftRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_rightTopRadius, cornerRadius).toFloat()
        rightRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_leftBottomRadius, cornerRadius).toFloat()
        topRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_rightBottomRadius, cornerRadius).toFloat()
        bottomRadius = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_leftTopRadius, cornerRadius).toFloat()
        rectColor = a.getColor(R.styleable.SmoothRoundedRectView_rectColor, Color.WHITE)
        drawBorderOnly = a.getBoolean(R.styleable.SmoothRoundedRectView_drawBorderOnly, false) // 获取 drawBorderOnly 属性，默认为 false
        strokeWidth = a.getDimensionPixelSize(R.styleable.SmoothRoundedRectView_strokeWidth, 1).toFloat() // 获取 drawBorderOnly 属性，默认为 false


        a.recycle() // 释放 TypedArray 资源
        init()
    }

    private fun init() {
        paint.color = rectColor
        paint.style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas) {

        // 计算圆角矩形的边界
        rectF.set(0f, 0f, width.toFloat(), height.toFloat())
        // 绘制圆角矩形路径
        path = roundPath.getSmoothRoundPath(rectF, Math.max(leftRadius, 0f), Math.max(topRadius, 0f), Math.max(rightRadius, 0f), Math.max(bottomRadius, 0f))

        if (drawBorderOnly) {
            // 仅绘制边框
            paint.style = Paint.Style.STROKE
            paint.strokeWidth = strokeWidth // 设置边框宽度，可以根据需要自行定义
        } else {
            // 绘制圆角矩形
            paint.style = Paint.Style.FILL
        }

        // 绘制圆角矩形或边框
        canvas.drawPath(path, paint)
    }
}
